package com.tmpt.controller.taglib;

import com.tmpt.utils.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.util.Map;

/**
 * Created by wxy on 2017/9/26.
 */
public class UrlAuthUtils {

    private HttpServletRequest request;
    public UrlAuthUtils(HttpServletRequest request){
        this.request = request;
    }

    public boolean authorizeUsingUrlCheck(String url)  {
        if(StringUtils.isNull(url))return true;

        String contextPath = request.getContextPath();
        Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
        boolean auth = false;
        try{
            auth = this.getPrivilegeEvaluator().isAllowed(contextPath, url, null, currentUser);
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            //e.printStackTrace();
        }
        return auth;
    }

    private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
        WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
        Map wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
        if(wipes.size() == 0) {
            throw new IOException("No visible WebInvocationPrivilegeEvaluator instance could be found in the application context. There must be at least one in order to support the use of URL access checks in \'authorize\' tags.");
        } else {
            return (WebInvocationPrivilegeEvaluator)wipes.values().toArray()[0];
        }
    }


}
